import { reqUserInfo, reqUserLogin, reqUserLogout, reqUserRefreshToken } from '@/api/users'
import { defineStore } from 'pinia'
import router from '@/router'

interface IToken {
  access_token: string
  token_type: string
  refresh_token: string
  expires_in: number
  user_id: string
}

type LoginInfo = {
  phone: string
  code?: string
  password: string
}
export const useUserStore = defineStore('user', () => {
  const tokenString = ref('')
  const userInfo = ref({})
  // 设置token格式类型
  const token = computed<IToken>(() => {
    try {
      userInfo.value = JSON.parse(window.localStorage.getItem('userInfo') || '{}')
      return JSON.parse(tokenString.value || window.localStorage.getItem('tokenInfo') || '{}')
    } catch (err) {
      ElMessage.error('Json字符串格式错误,转化对象失败...')
      throw err
    }
  })
  // 保存token
  // const saveToken = (data: string) => {
  //   tokenString.value = data
  //   window.localStorage.setItem('tokenInfo', data)
  // }
  // 用户登录
  const userLogin = async (loginInfo: LoginInfo) => {
    const { data } = await reqUserLogin(loginInfo)
    if (!data.success) {
      ElMessage.error('登录信息有误！')
      throw new Error(data.message)
    }
    tokenString.value = data?.content
    window.localStorage.setItem('tokenInfo', data?.content)
    await getUserInfo()
    ElMessage.success('用户登录成功')
    // TS 不能使用route获取redirect的参数，无法跳回到指定页面
    // router.push((route.query.redirect as string) || '/')
    const params = new URLSearchParams(window.location.search)
    const redirect = params.get('redirect')
    router.push(redirect || '/')
  }
  // 获取用户信息
  const getUserInfo = async () => {
    const { data } = await reqUserInfo()
    userInfo.value = data.content
    window.localStorage.setItem('userInfo', JSON.stringify(data.content))
  }

  // 用户退出
  const userLogout = async () => {
    await ElMessageBox.confirm('确认用户退出吗？', '退出询问', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).catch(() => {
      ElMessage.info('已取消！')
      return new Promise(() => {})
    })
    await reqUserLogout().catch(() => {})
    userInfo.value = {}
    tokenString.value = '{}'
    window.localStorage.clear() // removeItem()
    ElMessage.success('用户已退出！')
  }
  // 刷新Token
  let promiseRt: Promise<any>
  let isRefreshing = false
  const refreshToken = async () => {
    if (isRefreshing) {
      return promiseRt
    }
    isRefreshing = true
    promiseRt = await reqUserRefreshToken(token.value.refresh_token)
      .then((data) => {
        if (data.data.success) {
          window.localStorage.setItem('tokenInfo', data.data.content)
          tokenString.value = data.data.content
        } else {
          throw new Error('refresh_token失败')
        }
      })
      .catch(() => {
        throw new Error('reqUserRefreshToken失败')
      })
      .finally(() => {
        isRefreshing = false
      })
  }
  return { token, userInfo, userLogin, userLogout, getUserInfo, refreshToken }
})
